package com.example.admin.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.example.admin.base.ResponseResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

@RestController
@RequestMapping("/upload")

public class Uploadcon {
    @Autowired
    OSS ossClient;
    @Value("${zhyl.oss.bucketName}")
    String bucketName;
    @Value("${zhyl.oss.endPoint}")
    String endPoint;
    @PostMapping("/singleupload")

    public ResponseResult singleupload(MultipartFile file){
//        构建上传后，回显图片的名字
        String oldname = file.getOriginalFilename();
        int number = oldname.indexOf(".");
        String suffix = oldname.substring(number);
        String newname = System.currentTimeMillis()+suffix;
        HashMap<String, String> result = new HashMap<>();
        try {
            // 1. 创建存储空间（Bucket）
            // 2. 上传文件
//            String content = "Hello OSS";
            ossClient.putObject(bucketName, newname,file.getInputStream());
            System.out.println("2. 文件 " + newname + " 上传成功。");
            String filePath = "https://"+bucketName+"."+endPoint+"/"+newname;
            System.out.println(filePath);
            result.put("url",filePath);
        } catch (OSSException oe) {
            oe.getMessage();
            System.out.println("显示失败");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return ResponseResult.success(result);
    }
}
